<template>
  <view class="store-dashboard">
    <HeadNav title="列表页" bgColor="#fff" @getHeadHeight="getHeadHeight" :backIcon="true" path="/pages/index/index">
      <template #left>
        <view class="u-nav-slot">
          <image class="logo" :src="Logo" />
          <view class="flex items-center" @click="toChooseShop">
            <image class="location-icon" :src="IMG_URL2 + 'mine/location1.svg'" />
            <view class="shopname">{{ shopName }}</view>
            <image class="chevronright" :src="IMG_URL2 + 'common/chevron-right.svg'"></image>
          </view>
        </view>
      </template>
    </HeadNav>
    <view class="search-header" :style="{ top: `${HeadNavHeight}px` }">
      <div class="search-box">
        <search class="u-search-box" />
        <up-image :show-loading="true" :src="`${IMG_URL2}shopm/scan.svg`" width="24px" height="24px" bgColor="#fff"
          @click="scanCode"></up-image>
      </div>
    </view>
    <view class="mb-12" v-if="list5.length > 0">
      <up-swiper :list="list5"  @change="(e) => (currentValue = e.current)" :autoplay="true" :keyName="'images'"
        :height="'210px'" @click="goToDetail">
        <template #indicator>
          <view class="indicator">
            <view class="indicator__dot" v-for="(item, index) in list5" :key="index"
              :class="[index === currentValue && 'indicator__dot--active']" @click="goToDetail(item)">
            </view>
          </view>
        </template>
      </up-swiper>
    </view>
    <view class="tipscontent flex items-center justify-around">
      <view v-for="(item, index) in hometipsList" :key="index" class="flex items-center">
        <image class="tips-icon" :src="IMG_URL2 + 'common/check-circle1.svg'" mode="aspectFill" />
        <view>{{ item }}</view>
      </view>
    </view>
    <view class="hot-selling" >
      <view class="section-title" @click="handleCourseTap">
        <view>店铺数据</view>
        <view>
          <image class="chevronright" :src="IMG_URL2+'common/chevron-right.svg'"></image>
        </view>
      </view>
      <!-- <view class="hot-product" @click="handleCourseTap">
        <image class="dataimg" :src="IMG_URL2 + 'common/dataimg.jpg'" mode="aspectFill" />
      </view> -->
    </view>
    <view class="featured-products">
      <view class="section-title">
        爆款推荐
      </view>
      <scroll-view scroll-x class="product-scroll">
        <view class="product-item" v-for="product in featuredProducts" :key="product.productId"
          @click="onGoodsDetail(product)">
          <image :src="product.images" mode="aspectFill" />
          <view class="product-name">{{ product.productName }}</view>
          <view class="product-price">¥{{ product.price }}</view>
        </view>
      </scroll-view>
    </view>

    <view class="hot-selling">
      <view class="section-title" @click="onTargetPage('/pagesshop/onlineexhibitionhall/index')">
        <view>线上展厅</view>
        <view>
          <image class="chevronright" :src="IMG_URL2+'common/chevron-right.svg'"></image>
        </view>
      </view>
      <view class="hot-product">
        <view class="chart-section">
            <view v-for="(itemsrc, srcIndex) in onlineDataimagesList" :key="srcIndex" class="chart-item">
              <up-image :show-loading="true" :src="itemsrc"></up-image>
            </view>
          </view>
      </view>
    </view>

    <view class="recommended-products">
      <u-tabs :list="chartTabs" :current="currentChartTab" @change="onChartTabChange" lineColor="#c4996c"
        itemStyle="flex:1; height: 48px;" :activeStyle="{
          color: '#c4996c',
          fontWeight: 'bold'
        }" :inactiveStyle="{
          color: '#333',
          fontSize: '28rpx'
        }"></u-tabs>
      <Waterfall ref="waterfallRef" :loadStatus="loadStatus" :flowList.sync="goodsList" @addRandomData="addRandomData">
      </Waterfall>
    </view>
    <BackTop :backTop="backTop" />
    <SalesButton />
    <view class="popup-wrapper" v-if="showPopup">
      <view class="popup-content">
        <!-- 左侧图标 -->
        <view class="icon-wrapper">
          <u-icon name="warning-fill" color="#f56c6c" size="24"></u-icon>
        </view>
        
        <!-- 中间文本 -->
        <view class="message">
          <text class="main-text">请及时填写经营数据，</text>
          <text class="action-text" @click="handleAction">去填写</text>
        </view>
        
        <!-- 右侧关闭按钮 -->
        <view class="close-btn" @click="handleClose">
          <u-icon name="close" color="#999" size="20"></u-icon>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { IMG_URL2 } from "@/config";
import Logo from "@/static/logo.png";
import BackTop from "@/components/back-top.vue";
import HeadNav from "@/components/headnav.vue";
import SalesButton from "@/components/salesbutton.vue";

import Waterfall from "@/components/waterfall.vue";
import search from "@/components/search/search.vue";
import { shopApi } from "@/api";

let showPopup = ref(false);
// 商品瀑布流列表
const flowList = ref([]);
const goodsList = ref([]);
const waterfallRef = ref();
let currentValue=ref(0);
// 返回顶部
const backTop = ref(0);
const currentChartTab = ref(0);
const list5 = ref([]);
const chartTabs = [{ name: "推荐商品" }, { name: "最新上架" }];
let shopName = ref("");
let featuredProducts = ref([]);
let HeadNavHeight = ref(null);
let hometipsList = ref(["官方商城", "正品保障", "售后无忧"]);
let pageSize = ref(10);
let currentPage = ref(1);
let totalCount = ref(0);
let loadStatus = ref("正在加载中");

let onlineDataimagesList=ref([])


const goToDetail = (item) => {
  const tempItem = list5.value[item];
  uni.navigateTo({
    url: "/pages/good/details?id=" + tempItem.productId
  });
};

// 导航栏高度(单位px)
const getHeadHeight = (e) => {
  HeadNavHeight.value = e;
};
const toChooseShop = () => {
  uni.navigateTo({
    url: `/pagesshop/shop/shopmanage`
  });
};

// 商品详情
const onGoodsDetail = (item) => {
  uni.navigateTo({
    url: "/pages/good/details?id=" + item.productId
  });
};

const onTargetPage = (url) => {
  uni.navigateTo({
    url: url
  });
};

const onChartTabChange = (item) => {
  currentChartTab.value = item.index;
  currentPage.value = 1;
  goodsList.value = [];
  if (waterfallRef.value) {
    waterfallRef.value.onClear();
  }
  getData(Number(item.index + 1), 1);
};
// 监听页面滚动(返回顶部)
onPageScroll((e) => {
  backTop.value = e.scrollTop;
});
// 获取首页线上展厅
const getIndexExhibitionHall = () => {
  shopApi.EXHIBITIONHALLGETINDEXEXHIBITIONHALL().then((res) => {
    if (res && res.code == 200) {
      onlineDataimagesList.value = res.result.images?res.result.images.split(','):[]
    } else {
      uni.showToast({
        title: res.errMsg,
        icon: "success"
      });
    }
  });
};
const getBannerlist = () => {
  let data = {
    currentPage: 1,
    sorted: true,
    pageSize: 10
  };
  shopApi.BANNERGETLIST(data).then((res) => {
    if (res && res.code == 200) {
      list5.value = res.result.data;
    } else {
      uni.showToast({
        title: res.errMsg,
        icon: "success"
      });
    }
  });
};
const scanCode = () => {
  uni.scanCode({
    success: (res) => {
      console.log("扫码内容", res);
      getDataDetail(res.result);
      
    }
  });
};
const getDataDetail = (Id) => {
    shopApi.CATEGORYGETFRONTPRODUCTDETAILBYID({ id: Id }).then((res) => {
        if (res.code == 200) {
          uni.navigateTo({
            url: "/pages/good/details?id=" + res.result
          });
        } else{
            uni.showToast({
                title: res.errMsg,
                icon: "success",
            });
        }

    })
}
const getrecommendProductList = () => {
  let data = {
    currentPage: 1,
    pageSize: 20
  };
  shopApi.RECOMMENDPRODUCTGETLIST(data).then((res) => {
    if (res && res.code == 200) {
      featuredProducts.value = res.result.data;
    } else {
      uni.showToast({
        title: res.errMsg,
        icon: "success"
      });
    }
  });
};

const handleClose = () => {
  showPopup.value = false
}

const handleAction = () => {
  showPopup.value = false
  uni.navigateTo({
    url: '/pagesshop/businessdata/index'
  })
}

const getData = (sortType, type) => {
  let data = {
    currentPage: currentPage.value,
    sorted: true,
    pageSize: pageSize.value,
    sortType: sortType
  };
  shopApi.CATEGORYGETFRONTPRODUCTLIST(data).then((res) => {
    if (res && res.code == 200) {
      totalCount.value = res.result.totalCount;
      if (type == 1) {
        goodsList.value = res.result.data;
      } else {
        goodsList.value = res.result.data ? goodsList.value.concat(res.result.data) : [];
      }
    } else {
      uni.showToast({
        title: res.errMsg,
        icon: "success"
      });
    }
  });
};
const getcheckIsWriteShopData = () => {
  shopApi.SHOPCHECKISWRITESHOPDATA().then((res) => {
    if (res.code == 200) {
      showPopup.value = res.result
    }else {
      uni.showToast({
        title: res.errMsg,
        icon: "success"
      });
    }
  })
}
onShow(async () => {
  await getBannerlist();
  await getrecommendProductList();
  await getData(1, 1);
  await getIndexExhibitionHall()
  getShopData();
  getcheckIsWriteShopData()
});

// 触底加载
onReachBottom(() => {
  console.log("触底加载");
  if (goodsList.value.length >= totalCount.value) {
    loadStatus.value = "没有更多数据了";
    return;
  }
  loadStatus.value = "正在加载中";
  getData(Number(currentChartTab.value + 1), 1);
});
// 下拉刷新
onPullDownRefresh(() => {
  console.log("下拉刷新");
  // 瀑布流数据清空
  if (waterfallRef.value) {
    waterfallRef.value.onClear();
  }
  // 正常情况下接口返回应该很会很快。故意延迟调用，让用户有在刷新的体验感
  loadStatus.value = "loading";
  goodsList.value = [];
  currentPage.value = 1;
  getData(Number(currentChartTab.value + 1), 1);
  getBannerlist();
  getrecommendProductList();
  getIndexExhibitionHall()
  getShopData();
  getcheckIsWriteShopData()
  setTimeout(() => {
    uni.stopPullDownRefresh();
  }, 300);
});
const handleCourseTap = (course) => {
  uni.navigateTo({
    url: `/pagesshop/staff/homechart`,
    fail(err) {
    }
  })
}
const addRandomData = () => {
  // for (let i = 0; i < 8; i++) {
  //   let index = random(0, goodsList.value.length - 1);
  //   // 先转成字符串再转成对象，避免数组对象引用导致数据混乱
  //   let item = JSON.parse(JSON.stringify(goodsList.value[index]));
  //   item.id = guid(20);
  //   flowList.value.push(item);
  // }
};
const getShopData = () => {
  shopApi.SHOPGETCURRENTSHOPINFO().then((res) => {
    if (res.code == 200) {
      shopName.value = res.result.name;
    } else {
      uni.showToast({ title: res.errMsg, icon: "none" });
    }
  });
};
</script>

<style lang="scss" scoped>
.store-dashboard {
  background-color: #fff;
  padding-bottom: 100rpx;

  .u-nav-slot {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-color: $u-border-color;
    padding: 3px 7px;
    box-sizing: border-box;
    opacity: 0.8;

    .logo {
      width: 68rpx;
      height: 48rpx;
      margin-right: 10rpx;
    }

    .location-icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 10rpx;
    }

    .shopname {
      font-family: PingFang SC;
      font-size: 14px;
      font-weight: 400;
      line-height: 22px;
      color: rgba(0, 0, 0, 0.9);
    }

    .chevronright {
      width: 32rpx;
      height: 32rpx;
    }
  }

  .logo {
    width: 120rpx;
    height: 84rpx;
  }

  .search-header {
    background-color: #fff;
    padding: 20rpx;
    box-sizing: border-box;
    position: sticky;
    left: 0;
    z-index: 99;

    .store-info {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      text {
        font-size: 32rpx;
        font-weight: bold;
        margin: 0 10rpx;
      }
    }

    .search-box {
      display: flex;
      align-items: center;

      .u-search-box {
        width: 95%;
      }
    }
  }

  .indicator {
    display: flex;
    justify-content: center;

    &__dot {
      height: 6px;
      width: 6px;
      border-radius: 100px;
      background-color: rgba(255, 255, 255, 0.35);
      margin: 0 5px;
      transition: background-color 0.3s;

      &--active {
        background-color: #ffffff;
      }
    }
  }

  .tipscontent {
    font-family: PingFang SC;
    font-size: 12px;
    font-weight: 400;
    line-height: 20px;
    text-align: left;
    text-underline-position: from-font;
    text-decoration-skip-ink: none;
    color: rgba(0, 0, 0, 0.9);

    .tips-icon {
      width: 32rpx;
      height: 32rpx;
      margin-right: 10rpx;
      color: rgba(0, 0, 0, 0.9);
    }
  }

  .chart-container {
    flex: 1;
  }

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .chevronright {
      width: 16px;
      height: 16px;
    }
  }

  .featured-products,
  .hot-selling,
  .recommended-products {
    background-color: #fff;
    margin-top: 20rpx;
    padding: 20rpx;
    box-sizing: border-box;

    .product-scroll {
      white-space: nowrap;

      .product-item {
        display: inline-block;
        margin-right: 20rpx;
        width: 200rpx;

        image {
          width: 200rpx;
          height: 200rpx;
          border-radius: 10rpx;
        }

        .product-name {
          font-size: 24rpx;
          margin-top: 10rpx;
        }

        .product-price {
          font-size: 28rpx;
          color: #c4996c;
          font-weight: bold;
        }
      }
    }
  }

  .hot-selling {
    .dataimg{
      width: 100%;
    }
    .hot-product {
      position: relative;

      image {
        width: 100%;
        height: 300rpx;
        border-radius: 10rpx;
      }

      .product-info {
        position: absolute;
        bottom: 20rpx;
        left: 20rpx;
        color: #fff;

        .product-name {
          font-size: 32rpx;
          margin-bottom: 10rpx;
        }

        .product-price {
          font-size: 36rpx;
          font-weight: bold;
        }
      }
    }
  }

  .recommended-products {
    .product-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20rpx;

      .product-card {
        background-color: #fff;
        border-radius: 10rpx;
        overflow: hidden;

        image {
          width: 100%;
          height: 300rpx;
        }

        .product-info {
          padding: 20rpx;
          box-sizing: border-box;

          .product-name {
            font-size: 28rpx;
            margin-bottom: 10rpx;
          }

          .product-price {
            font-size: 32rpx;
            color: #c4996c;
            font-weight: bold;
          }
        }
      }
    }
  }
}
.popup-wrapper {
  position: fixed;
  top: 110px;
  left: 0;
  right: 0;
  z-index: 999;
  padding: 20rpx;
  
  .popup-content {
    position: relative;
    display: flex;
    align-items: center;
    padding: 24rpx;
    background-color: #fff9f2;
    border-radius: 8rpx;
    // border: 2rpx solid #8a2be2;
    
    .icon-wrapper {
      margin-right: 16rpx;
      display: flex;
      align-items: center;
    }
    
    .message {
      flex: 1;
      font-size: 28rpx;
      
      .main-text {
        color: #333;
      }
      
      .action-text {
        color: #ff6b00;
      }
    }
    
    .close-btn {
      padding: 10rpx;
      margin: -10rpx;
      display: flex;
      align-items: center;
    }
  }
}
</style>
